import { loadingController, toastController, alertController } from '@ionic/vue';
import configService from '@/utils/config';

// 加载框样式配置
const mLoadingOptions = {
  animated: true,
  backdropDismiss: false,
  duration: 20000,
  keyboardClose: true,
  message: '数据加载中...',
  mode: 'ios' as "ios" | "md",
  showBackdrop: true,
  spinner: 'circles' as "bubbles" | "circles" | "circular" | "crescent" | "dots" | "lines" | "lines-small" | null | undefined,
  translucent: true
}
export class PublicService {
  // public responseStatus = false;
  public loading: any;
  // 工具方法实例
  private static publicService: PublicService;

  /**
   * 获取工具类实例
   * @param map 外部传入地图对象
   * @returns 
   */
  public static getInstance(): PublicService {
    if (this.publicService == null) {
      this.publicService = new PublicService();
    }
    return PublicService.publicService;
  }
  async thsToast(msg: string, duration = 2000) {
    const toast = await toastController
      .create({
        message: msg,
        duration: duration
      })
    return toast.present();
  }

  async Thsloading(message?: string): Promise<any> {
    mLoadingOptions.message = message || '数据加载中...';
    const loading = await loadingController
      .create(mLoadingOptions);
    await loading.present()
    return loading;
  }

  closeLoading(loading: any) {
    if (loading) {
      loading.then((res: { dismiss: () => void; }) => {
        res.dismiss();
        // this.responseStatus = false;
      });
    }
  }

  async thsPromptAlert(header: string, message: string, callback: any, cancelBack?: any) {
    const alert = await alertController
      .create({
        cssClass: 'my-custom-class',
        header: header,
        message: message,
        id: 'thsPromptAlert',
        htmlAttributes: {
          'aria-label': 'alert dialog',
        },
        buttons: [
          {
            text: '取消',
            role: 'cancel',
            cssClass: 'cancelBtn',
            id: 'cancel-button',
            handler: () => {
              cancelBack && (cancelBack());
            },
          },
          {
            text: '确定',
            id: 'confirm-button',
            cssClass: 'comfirmBtn',
            handler: () => {
              callback();
            },
          },
        ],
      });
    return alert.present();
  }

  async alertConfirm(header: string, message: string, callback: any) {
    const alert = await alertController.create({
      header: ' 温馨提示',
      message: '即将开始记录你的轨迹',
      buttons: [
        {
          text: '确定',
          handler: () => {    // 获取表单输入的值
            callback();
          }
        }
      ]
    });
    await alert.present();
  }

  /**
   * 日期对象转为日期字符串
   * @param date 需要格式化的日期对象
   * @param sFormat 输出格式,默认为yyyy-MM-dd                        年：y，月：M，日：d，时：h，分：m，秒：s
   * @example  dateFormat(new Date())                               "2017-02-28"
   * @example  dateFormat(new Date(),'yyyy-MM-dd')                  "2017-02-28"
   * @example  dateFormat(new Date(),'yyyy-MM-dd HH:mm:ss')         "2017-02-28 13:24:00"   ps:HH:24小时制
   * @example  dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss')         "2017-02-28 01:24:00"   ps:hh:12小时制
   * @example  dateFormat(new Date(),'hh:mm')                       "09:24"
   * @example  dateFormat(new Date(),'yyyy-MM-ddTHH:mm:ss+08:00')   "2017-02-28T13:24:00+08:00"
   * @example  dateFormat(new Date('2017-02-28 13:24:00'),'yyyy-MM-ddTHH:mm:ss+08:00')   "2017-02-28T13:24:00+08:00"
   */
  dateFormat(date: any, sFormat: string) {
    if (!date) {
      return ''
    }
    date = new Date(date);
    const time = {
      Year: 0,
      TYear: '0',
      Month: 0,
      TMonth: '0',
      Day: 0,
      TDay: '0',
      Hour: 0,
      THour: '0',
      hour: 0,
      Thour: '0',
      Minute: 0,
      TMinute: '0',
      Second: 0,
      TSecond: '0',
      Millisecond: 0
    };
    time.Year = date.getFullYear();
    time.TYear = String(time.Year).substr(2);
    time.Month = date.getMonth() + 1;
    time.TMonth = time.Month < 10 ? '0' + time.Month : String(time.Month);
    time.Day = date.getDate();
    time.TDay = time.Day < 10 ? '0' + time.Day : String(time.Day);
    time.Hour = date.getHours();
    time.THour = time.Hour < 10 ? '0' + time.Hour : String(time.Hour);
    time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;
    time.Thour = time.hour < 10 ? '0' + time.hour : String(time.hour);
    time.Minute = date.getMinutes();
    time.TMinute = time.Minute < 10 ? '0' + time.Minute : String(time.Minute);
    time.Second = date.getSeconds();
    time.TSecond = time.Second < 10 ? '0' + time.Second : String(time.Second);
    time.Millisecond = date.getMilliseconds();

    return sFormat.replace(/yyyy/ig, String(time.Year))
      .replace(/yyy/ig, String(time.Year))
      .replace(/yy/ig, time.TYear)
      .replace(/y/ig, time.TYear)
      .replace(/MM/g, time.TMonth)
      .replace(/M/g, String(time.Month))
      .replace(/dd/ig, time.TDay)
      .replace(/d/ig, String(time.Day))
      .replace(/HH/g, time.THour)
      .replace(/H/g, String(time.Hour))
      .replace(/hh/g, time.Thour)
      .replace(/h/g, String(time.hour))
      .replace(/mm/g, time.TMinute)
      .replace(/m/g, String(time.Minute))
      .replace(/ss/ig, time.TSecond)
      .replace(/s/ig, String(time.Second))
      .replace(/fff/ig, String(time.Millisecond));
  }

  /**
   * @description: 获取当前日期是星期几
   * @params dateString 日期
   * @return 星期几
   */
  getWeekDate(dateString: string) {
    if (!dateString) {
      return
    }
    const now = new Date(dateString);
    const day = now.getDay();
    const weeks = ['周日',
      '周一',
      '周二',
      '周三',
      '周四',
      '周五',
      '周六'];
    const week = weeks[day];
    return week;
  }

  /**
   * @description: 获取月份有多少天
   * @params date ('2023-07-12')
   * @return 月有多少天（number）
   */
  getMonthNum(date: string) {
    const dateArr = date.split('-');
    const year = Number(dateArr[0]);
    let month = dateArr[1];
    if (month.slice(0, 1) === '0') {
      month = month.slice(1);
    }
    return new Date(year, Number(month), 0).getDate();
  }

  /**
  * 根据返回值处理aqi状态渐变背景颜色
  * @param val val为aqi状态
  */
  handleBgColor(val: string) {
    if (val.indexOf('优') > -1) {
      return '#00e400';
    } else if (val.indexOf('良') > -1) {
      return '#ffcd35';
    } else if (val.indexOf('轻度污染') > -1) {
      return '#ff7e00';
    } else if (val.indexOf('中度污染') > -1) {
      return '#dd4209';
    } else if (val.indexOf('重度污染') > -1) {
      return '#99004c';
    } else if (val.indexOf('严重污染') > -1) {
      return '#46072d';
    }
  }
  /**
   * AQI数据处理
   * @param value AQI值
   */
  setAQIPollutionColor(value: any) {
    const valueArr: any = typeof value === 'string' && value.indexOf('~') !== -1 ?
      value.split('~') : typeof value === 'string' ? [value] : [];
    const status = {
      status: '--',
      className: 'aqi_legend-0'
    };
    if (valueArr.length === 1) {
      if (valueArr[0] * 1 >= 0 && valueArr[0] * 1 <= 50) {
        status.status = '优';
        status.className = 'aqi_legend-1';
      } else if (valueArr[0] * 1 > 50 && valueArr[0] * 1 <= 100) {
        status.status = '良';
        status.className = 'aqi_legend-3';
      } else if (valueArr[0] * 1 > 100 && valueArr[0] * 1 <= 150) {
        status.status = '轻度污染';
        status.className = 'aqi_legend-5';
      } else if (valueArr[0] * 1 > 150 && valueArr[0] * 1 <= 200) {
        status.status = '中度污染';
        status.className = 'aqi_legend-7';
      } else if (valueArr[0] * 1 > 200 && valueArr[0] * 1 <= 300) {
        status.status = '重度污染';
        status.className = 'aqi_legend-9';
      } else if (valueArr[0] * 1 > 300) {
        status.status = '严重污染';
        status.className = 'aqi_legend-11';
      }

    } else if (valueArr.length === 2) {
      if (valueArr[0] * 1 >= 0 && valueArr[0] * 1 <= 50 && valueArr[1] * 1 <= 50) {
        status.status = '优';
        status.className = 'aqi_legend-1';
      } else if (valueArr[0] * 1 > 50 && valueArr[0] * 1 <= 100 && valueArr[1] * 1 <= 100) {
        status.status = '良';
        status.className = 'aqi_legend-3';
      } else if (valueArr[0] * 1 > 100 && valueArr[0] * 1 <= 150 && valueArr[1] * 1 <= 150) {
        status.status = '轻度污染';
        status.className = 'aqi_legend-5';
      } else if (valueArr[0] * 1 > 150 && valueArr[0] * 1 <= 200 && valueArr[1] * 1 <= 200) {
        status.status = '中度污染';
        status.className = 'aqi_legend-7';
      } else if (valueArr[0] * 1 > 200 && valueArr[0] * 1 <= 300 && valueArr[1] * 1 <= 300) {
        status.status = '重度污染';
        status.className = 'aqi_legend-9';
      } else if (valueArr[0] * 1 > 300) {
        status.status = '严重污染';
        status.className = 'aqi_legend-11';
      }
      if (valueArr[0] * 1 >= 0 && valueArr[0] * 1 <= 50 && valueArr[1] * 1 > 50 && valueArr[1] * 1 <= 100) {
        status.status = '优~良';
        status.className = 'aqi_legend-2';
      } else if (valueArr[0] * 1 > 50 && valueArr[0] * 1 <= 100 && valueArr[1] * 1 > 100 && valueArr[1] * 1 <= 150) {
        status.status = '良~轻度污染';
        status.className = 'aqi_legend-4';
      } else if (valueArr[0] * 1 > 100 && valueArr[0] * 1 <= 150 && valueArr[1] * 1 > 150 && valueArr[1] * 1 <= 200) {
        status.status = '轻度污染~中度污染';
        status.className = 'aqi_legend-6';
      } else if (valueArr[0] * 1 > 150 && valueArr[0] * 1 <= 200 && valueArr[1] * 1 > 200 && valueArr[1] * 1 <= 300) {
        status.status = '中度污染~重度污染';
        status.className = 'aqi_legend-8';
      } else if (valueArr[0] * 1 > 200 && valueArr[0] * 1 <= 300 && valueArr[1] * 1 > 300) {
        status.status = '重度污染~严重污染';
        status.className = 'aqi_legend-10';
      } else if (valueArr[0] * 1 > 300 && valueArr[1] * 1 > 300) {
        status.status = '严重污染';
        status.className = 'aqi_legend-11';
      }
    }
    return status;
  }
  /**
  * 处理污染数据，并返回相应状态和背景颜色
  * @param name 污染物名称
  * @param value 污染物数值
  */
  setPollutionColor(name: string, value: any) {
    let arr: any;
    switch (name) {
      case 'AQI': arr = [300, 200, 150, 100, 50]; break;
      case 'PM10': arr = [420, 350, 250, 150, 50]; break;
      case 'PM2_5' || 'PM2.5': arr = [250, 150, 115, 75, 35]; break;
      case 'SO2': arr = [1600, 800, 650, 500, 150]; break;
      case 'NO2': arr = [2340, 1200, 700, 200, 100]; break;
      case 'CO': arr = [90, 60, 35, 10, 5]; break;
      case 'O3': arr = [800, 400, 300, 200, 160]; break;
      //  default: return false;
    }

    let bg = '', // 污染物背景
      boxBg = '', // 污染物父盒子背景
      status = '', // 污染物状态
      rate = '0%'; // 污染物百分比
    if (!value || value === '—') {
      bg = '#ccc';
      boxBg = 'rgba(200,200,200,0.3)';
      status = '--';
    } else if (value > arr[0]) {
      bg = '#46072d';
      boxBg = 'rgba(70,0,13,0.3)';
      status = '严重';
    } else if (value > arr[1]) {
      bg = '#99004c';
      boxBg = 'rgba(156,0,76,0.3)';
      status = '重度';
    } else if (value > arr[2]) {
      bg = '#dd4209';
      boxBg = 'rgba(255,0,0,0.3)';
      status = '中度';
    } else if (value > arr[3]) {
      bg = '#ff7e00';
      boxBg = 'rgba(255,126,0,0.3)';
      status = '轻度';
    } else if (value > arr[4]) {
      bg = '#e1b701';
      boxBg = 'rgba(107,205,7,0.3)';
      status = '良好';
    } else {
      bg = '#51d044';
      boxBg = 'rgba(0,193,64,0.3)';
      status = '优';
    }
    rate = ((value / arr[0]) * 100).toFixed(2) + '%';
    const rateVal = ((value / arr[0]) * 100).toFixed(0);
    return { bg, boxBg, status, rate, rateVal };
  }

  /**
   * 截取首要污染物字符串
   * @param val 首要污染物
   */
  substr(val: string) {
    if (!val || val === '—') {
      return '—';
    }
    if (val.indexOf('PM2.5') > -1 || val.indexOf('PM2.5') > -1) {
      return 'PM<sub>2.5</sub>';
    } else if (val.indexOf('PM10') > -1) {
      return 'PM<sub>10</sub>';
    } else if (val.indexOf('SO2') > -1) {
      return 'SO<sub>2</sub>';
    } else if (val.indexOf('CO') > -1) {
      return 'CO';
    } else if (val.indexOf('NO2') > -1) {
      return 'NO<sub>2</sub>';
    } else if (val.indexOf('O3') > -1) {
      return 'O<sub>3</sub>';
    }
  }
}

/**
 * 处理无数据
 * @param value 值
 * @return string
 */
export function handleNoVal(value: unknown) {
  if (value === null || value === undefined || value === '') {
    return '--';
  }
  return value;
}


/**
 * @description: 设置文件类型
 * @param {*} type
 * @return {*}
 */
export const setFileType = (type: string) => {
  if (type.toLocaleLowerCase().includes('ex')) {
    return 'excl'
  } else if (type.toLocaleLowerCase().includes('jp') || type.toLocaleLowerCase().includes('png')) {
    return 'img'
  } else if (type.toLocaleLowerCase().includes('doc')) {
    return 'doc'
  } else if (type.toLocaleLowerCase().includes('pdf')) {
    return 'pdf'
  } else {
    return 'text'
  }
}

/**
 * @description: 文件路径格式化
 * @param {string} filePath 文件路径
 * @return {*}
 */
export const formatFilePath = (filePath: string) => {
  let url = ''
  try {
    url = filePath.split('/')[2]
    url = url.substring(0, url.indexOf('.'))
  } catch (error) {
    new PublicService().thsToast('文件路径不正确')
  }
  // return `${configService.meetSummaryDownload}/${url}`
};

/**
 * 获取附件预览地址
 * @param {string} fileId 附件id
 */
export const getFilePreviewUrl = (fileId: string) => `${configService.fileHOST}${fileId}${configService.preview}`

/**
 * @description: 整改时限
 * @param {string} date 时间
 * @return {*}
 */
export const testLimitTime = (date: string) => {
  if (isNaN(new Date(date).getTime())) {
    return "";
  } else {
    return date
  }
};